<template>
	<d2-container>
	<div class="form-area">
		<el-form ref="updateForm" :model="updateForm" :rules="rules" label-width="140px" style="width: 80%; height:auto;">
			<div class="form-title">
				<h3>基本信息</h3>
			</div>
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="调拨原因" prop="applyReason">
						<el-input v-model="updateForm.applyReason" placeholder="请输入调拨原因"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="调拨单编号" prop="orderNo">
						<el-input  v-model="updateForm.orderNo" disabled></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="调出仓库" prop="repositoryNameOut">
						<el-select v-model="updateForm.repositoryNameOut" placeholder="请选择仓库"
						 @change="selectRepositoryOut()" style="width: 100%;">
							<el-option
									v-for="item in repositorys"
									:key="item.id"
									:label="item.repositoryName"
									:value="`${item.id}|${item.repositoryName}|${item.stockType}|${item.shopId}`">
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="调入仓库" prop="repositoryNameIn">
						<el-select v-model="updateForm.repositoryNameIn" placeholder="请选择仓库"
						 @change="selectRepositoryIn()" style="width: 100%;">
							<el-option
									v-for="item in repositorys"
									:key="item.id"
									:label="item.repositoryName"
									:value="`${item.id}|${item.repositoryName}|${item.stockType}|${item.shopId}`">
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="调拨日期" prop="applyDate">
						<el-date-picker
							v-model="updateForm.applyDate"
							type="date"
							range-separator="至"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							align="right"
							style="width: 100%;"
							></el-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="调拨状态" prop="allocationStatus">
						<el-select v-model="updateForm.allocationStatus" disabled style="width: 100%;">
							<el-option value="0" label="未处理"></el-option>
							<el-option value="1" label="已确定"></el-option>
							<el-option value="2" label="已撤销"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="24">
					<el-form-item label="备注" prop="remark">
						<el-input type="textarea" :rows="2" v-model="updateForm.remark" placeholder="请输入备注" ></el-input>
					</el-form-item>
				</el-col>
			</el-row>

			<div class="form-title">
			    <h3>系统信息</h3>
		    </div>
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="创建时间" prop="createTime">
						<el-input v-model="createTime" disabled></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="创建人" prop="creator">
						<el-input  v-model="creator" disabled></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="编辑时间" prop="reviseTime">
						<el-input v-model="reviseTime" disabled></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="编辑人" prop="reviser">
						<el-input  v-model="reviser" disabled></el-input>
					</el-form-item>
				</el-col>
			</el-row>

		</el-form>

		<div class="form-title">
			<h3>调拨商品信息</h3>
		</div>
		<div class="order-sku-list">
			<el-button type="primary" class="form-cancle-btn" @click="showDialog">添加调拨商品</el-button>
			<span>选择调出仓库后，仅可选择该仓库下的商品进行调拔。</span>
			<el-table :data="detailTableData" stripe border style="width: 100%" >
				    <el-table-column type="index" fixed label="序号" width="50"></el-table-column>
					<el-table-column label="商品名称" prop="productName" width="200"></el-table-column>
					<el-table-column label="商品编码" prop="productCode" width="200"></el-table-column>
					<el-table-column label="SKU名称" prop="productSkuName" width="200"></el-table-column>
					<el-table-column label="SKU编码" prop="productSkuCode" width="200"></el-table-column>
					<el-table-column label="商品条码" prop="productBarCode" width="200"></el-table-column>
					<el-table-column label="可用库存数量" prop="stockQuantity" width="200">
						<template slot="header">
							<span>可用库存数量</span>
							<el-button type="success" icon="el-icon-check" size="mini" plain @click="freshData()">刷新</el-button>
						</template>
					</el-table-column>
					<el-table-column label="单位" prop="unitName" ></el-table-column>
					<el-table-column label="调拨数量" prop="allocationQuantity" width="200">
						<template slot-scope="scope">
							<el-input-number v-model="scope.row.allocationQuantity" size="small" placeholder="请输入数量"
							 :min="0" :max="scope.row.quantity" style="width:100%">
							</el-input-number>
						</template>
					</el-table-column>		
			</el-table>
		</div>
		<div style="text-align: center;">
			<el-row :gutter="20">
				<el-col :span="24">
					<div class="form-submit">
					<el-button class="form-cancle-btn" @click="closePage">取消</el-button>
					<el-button @click="saveAllocation('updateForm',0)" class="form-submit-btn" type="primary">保存</el-button>
					<el-button @click="saveAllocation('updateForm',1)" class="form-submit-btn" type="primary">保存并提交</el-button>
				    </div>
				</el-col>
			</el-row>
		</div>
		<el-dialog title="调拨商品" :visible.sync="dialogVisible" width="80%" :before-close="handleClose">
			<el-table :data="productTableData" stripe border style="width: 100%" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55"></el-table-column>
				<el-table-column label="商品名称" prop="productName" width="250"></el-table-column>
				<el-table-column label="商品编码" prop="productCode" width="200"></el-table-column>
				<el-table-column label="SKU名称" prop="productSkuName" width="250"></el-table-column>
				<el-table-column label="SKU编码" prop="productSkuCode" width="200"></el-table-column>
				<el-table-column label="商品条码" prop="productBarCode" width="200"></el-table-column>
				<el-table-column label="库存数量" prop="stockQuantity" ></el-table-column>
				<el-table-column label="单位" prop="unitName" ></el-table-column>				
			</el-table>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="confirmSelectProduct">确 定</el-button>
			</span>
		</el-dialog>
	</div>
	</d2-container>
</template>

<script>
import { mapActions, mapState } from 'vuex'
import { queryAllocationOrder,saveOrUpdateAllocationOrder,queryStockProducts } from '@api/allocation/allocation'
import { findAllList} from "@api/repository/repositoryInfo";
import dayjs from 'dayjs'
export default {
  data () {
    return {
	  repositorys:[],
	  dialogVisible:false,
	  updateForm:{
		applyReason:null,
		shopIdOut:null,
		repositoryIdOut:null,
		repositoryNameOut:null,
		stockTypeOut:null,
		shopIdIn:null,
		repositoryIdIn:null,
		repositoryNameIn:null,
		stockTypeIn:null,
		remark:null,
		applyDate:null,
		allocationStatus:'0',
		auditStatus:0,
		allocationOrderDetails:[]
	  },
	  createTime: '',
	  creator: '',
	  reviseTime: '',
	  reviser: '',
	  multipleSelection: [],
	  detailTableData:[],
	  productTableData:[],
	  // 表单验证规则
      rules: {
        applyReason: [{ required: true, message: '请输入调拨原因', trigger: 'blur' }],
        repositoryNameOut: [{ required: true, message: '请选择调出仓库', trigger: 'blur' }],
        repositoryNameIn: [{ required: true, message: '请选择调入仓库', trigger: 'blur' }],
        applydate: [{ required: true, message: '请选择调拨日期', trigger: 'blur' }],
		productTableData: [{ required: true, message: '请添加调拨商品', trigger: 'change' }]
      },
	  
    }
  },
  computed: {
	  ...mapState('d2admin/page', ['opened', 'current']), // 用户获取当前页面的地址，用于关闭
  },
  mounted() {
    this.findRepositorys();
  },
  methods: {
    ...mapActions('d2admin/page', ['close']),
    findRepositorys(){
      findAllList().then((res) => {
          this.repositorys=res.data
      }).catch((err) => {
          console.log("err", err);
          this.loading = false;
        });
    },
	fetchData(){
		queryAllocationOrder({allocationOrderId:this.allocationOrderId}).then(res => {
			this.allocationOrder=res.data
			this.createTime=dayjs(this.allocationOrder.createTime).format('YYYY-MM-DD HH:mm:ss')
			this.reviseTime=dayjs(this.allocationOrder.reviseTime).format('YYYY-MM-DD HH:mm:ss')
			this.detailTableData=this.allocationOrder.allocationOrderDetails
			this.updateForm.id=this.allocationOrder.id
			this.updateForm.orderNo=this.allocationOrder.orderNo
			this.updateForm.applyReason=this.allocationOrder.applyReason
			this.updateForm.applyDate=this.allocationOrder.applyDate
			this.updateForm.shopIdOut=this.allocationOrder.shopIdOut
			this.updateForm.repositoryIdOut=this.allocationOrder.repositoryIdOut
			this.updateForm.repositoryNameOut=this.allocationOrder.repositoryNameOut
			this.updateForm.stockTypeOut=this.allocationOrder.stockTypeOut
			this.updateForm.shopIdIn=this.allocationOrder.shopIdIn
			this.updateForm.repositoryIdIn=this.allocationOrder.repositoryIdIn
			this.updateForm.repositoryNameIn=this.allocationOrder.repositoryNameIn
			this.updateForm.stockTypeIn=this.allocationOrder.stockTypeIn
			this.updateForm.remark=this.allocationOrder.remark
			this.loading = false

		}).catch(err => {
			console.log('err', err)
			this.loading = false
		})
	},
    closePage () { // 关闭当前窗口
	  let tagName = this.current
	  this.close({ tagName })
    },
	selectRepositoryOut(){
		if (this.updateForm.repositoryNameOut) {
			const [key,lable,stockType,shopId] = this.updateForm.repositoryNameOut.split('|')
			this.updateForm.repositoryIdOut = key
			this.updateForm.repositoryNameOut = lable
			this.updateForm.stockTypeOut = stockType
			this.updateForm.shopIdOut = shopId
		}

	},
	selectRepositoryIn(){
		if (this.updateForm.repositoryNameIn) {
			const [key,lable,stockType,shopId] = this.updateForm.repositoryNameIn.split('|')
			this.updateForm.repositoryIdIn = key
			this.updateForm.repositoryNameIn = lable
			this.updateForm.stockTypeIn = stockType
			this.updateForm.shopIdIn = shopId
		}
	},
	saveAllocation(formName,type){
		this.$refs[formName].validate(valid => {
        if (valid) {

			//调出仓库和调入仓库不能同为一个仓库
			if(this.updateForm.repositoryIdOut == this.updateForm.repositoryIdIn){
			 this.$message({
              message: '调出仓库和调入仓库不能同为一个仓库',
              type: 'warning'
             })
			 return
		    }

		this.updateForm.auditStatus=type
		if(this.detailTableData.length<1){
			this.$message({
              message: '请先选择调拨商品',
              type: 'warning'
            })
			return
		}

		let isFlag = false
		this.detailTableData.forEach(item => {
			if(item.allocationQuantity==undefined || item.allocationQuantity==0) {
				isFlag = true
			}
		})
		if(isFlag) {
			this.$message({
                message: '调拨数量必须大于0',
                type: 'warning'
            })
			return
		}

		// console.log(JSON.stringify(this.detailTableData))
		this.updateForm.allocationOrderDetails=this.detailTableData
		// console.log(JSON.stringify(this.updateForm))
		
		saveOrUpdateAllocationOrder(this.updateForm).then(res => {
			if (res.code == '000000') {
                this.$message({ message: res.message, type: "success" });
			    this.closePage()
            } else {
                this.$message({message: res.message, type:'error'});
                return;
            }
			this.loading = false
		}).catch(err => {
			console.log('err', err)
			this.loading = false
		})

		} else {
          console.log('error submit!!')
          return false
        }
      })
	},
	showDialog(){
		if(this.updateForm.repositoryIdOut==null){
			this.$message({
              message: '请选择调出仓库',
              type: 'warning'
            })
			return
		}
		this.dialogVisible=true
		queryStockProducts({ repositoryId: this.updateForm.repositoryIdOut }).then(res => {
			this.productTableData = res.data
			this.loading = false
		}).catch(err => {
			console.log('err', err)
			this.loading = false
		})
		this.dialogVisible=true
	},
	freshData() {
		if(this.detailTableData.length > 0) {
			queryStockProducts({ repositoryId: this.updateForm.repositoryIdOut }).then(res => {
				let list = res.data
				this.detailTableData.forEach(item => {
					list.forEach(item2 => {
						if(item2.stockId == item.stockId) {
							item.stockQuantity = item2.stockQuantity;
						}
					})
				})
				this.loading = false
		})
		}
		
	},

	handleSelectionChange (val) {
      this.multipleSelection = val
    },
	confirmSelectProduct(){
		this.multipleSelection.forEach(item => {
			if(!this.checkItem(item)){
				this.detailTableData.push(item)
			}
		})
		this.dialogVisible=false
	},
	checkItem(item) {
		let check = false;
		this.detailTableData.forEach(item2 => {
			if(item.stockId==item2.stockId){
				check = true
			}
		})
		return check;
	},
	handleClose(done) {
		this.$confirm('确认关闭？')
		.then(_ => {
			done();
		}).catch(_ => {});
	}
  },
  created () {
	this.allocationOrderId =  sessionStorage.getItem("allocationOrderIdUpdate")
	this.fetchData()
	this.freshData()
  }
}
</script>

<style lang="scss" scoped>
.order-details {
	padding: 20px;
	.order-number {
		width: 100%;
		height: 60px;
		align-items: center;
		display: flex;
		border:#666 1px 
		span {
			font-size: 14px;
			color: #333;
			margin: 30px 30px 30px 30px;
		}
	}

	.order-progress {
		width: 100%;
		align-items: center;
		display: flex;
		padding: 50px 0;
		.order-status {
			width: 250px;
			text-align: center;
			flex: 0 0 100px;
			h3 {
				font-size: 24px;
				color: #333;
			}
			p {
				font-size: 14px;
				color: #999;
				margin-top: 10px;
			}
		}
		.order-progress-bar {
			flex: 1 1 auto;
		}
	}

	.order-details-info {
		width: 100%;
		.table-list {
			p {
				font-size: 14px;
				color: #666;
				margin: 3px 0;
			}
		}
	}

	.order-sku-list {
		width: 100%;
		margin-top: 30px;
		.sku-info {
			width: 100%;
			display: flex;
			.sku-image {
				width: 80px;
				height: 80px;
				flex: 0 0 80px;
			}
			.sku-details {
				flex: 1 1 auto;
				h3 {
					font-size: 14px;
					color: #333;
					padding-left: 30px;
				}
				p {
					font-size: 14px;
					color: #999;
					margin-top: 4px;
					padding-left: 30px;
				}
			}
		}
		.sku-summary {
			border: #ebeef5 1px solid;
			border-top: none;
			justify-content: flex-end;
			display: flex;
			padding: 20px;
			.sku-summary-content {
				width: 240px;
				p {
					width: 100%;
					font-size: 14px;
					color: #333;
					justify-content: space-between;
					display: flex;
					margin: 5px 0;
				}
				span {
					font-size: 14px;
				}
				span.sku-summary-text {
					font-size: 18px;
					font-weight: bold;
					color: #ff5642;
				}
			}
		}
	}
}

::v-deep .el-table thead.is-group th {
	background: #fff!important;
}
.warning-text {
	color: #ff5642;
}
.success-text {
	color: #1aa57b;
}
</style>
